package com.yjha.huazhubusiness.utils;


import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjha.huazhubusiness.bean.XyxtXyxxJbxxb;
import com.yjha.huazhubusiness.vo.XyxtXyxxJbxxbVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: ywm;
 * @CreateTime: 2025-07-15
 * @Description:
 * @Version: 1.0
 */
@Component
public class HzUtils {

	@Value("${hz.url.addUserUrl}")
	String  addUserUrl;
	@Value("${hz.cardId}")
	String cardId;
	@Value("${hz.cardPassWord}")
	String cardPassWord;
	@Value("${hz.certificateType}")
	String certificateType;
	@Value("${hz.url.getHxUserUrl}")
	String getHxUserUrl;

	public String doPost(String httpUrl, String clientId, String secret) {
		// 创建时间格式化器
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		StringBuffer result = new StringBuffer();
		HttpURLConnection connection = null;
		OutputStream os = null;
		InputStream is = null;
		BufferedReader br = null;

		try {
			URL url = new URL(httpUrl);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(3000);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

			// 设置Basic认证
			String credentials = clientId + ":" + secret;
			String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes("utf-8"));
			String authHeader = "Basic " + encodedCredentials;
			connection.setRequestProperty("Authorization", authHeader);

			// 发送请求
			connection.connect();

			// 获取响应状态
			int responseCode = connection.getResponseCode();
			String responseMessage = connection.getResponseMessage();

			// 读取响应体
			if (responseCode >= 200 && responseCode < 300) {
				is = connection.getInputStream();
			} else {
				is = connection.getErrorStream();
			}

			if (is != null) {
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String temp;
				while ((temp = br.readLine()) != null) {
					result.append(temp);
				}
			}

			return result.toString();

		} catch (MalformedURLException e) {
			System.err.println("URL格式错误: " + httpUrl);
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("HTTP请求IO异常");
			e.printStackTrace();

			// 尝试获取错误响应信息
			if (connection != null) {
				try {
					is = connection.getErrorStream();
					if (is != null) {
						br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
						String temp;
						result.setLength(0); // 清空之前的内容
						while ((temp = br.readLine()) != null) {
							result.append(temp);
						}
					}
				} catch (IOException ex) {
				}
			}
		} finally {
			// 关闭资源
			try {
				if (br != null) br.close();
				if (os != null) os.close();
				if (is != null) is.close();
			} catch (IOException e) {
				System.err.println("关闭资源时出错: " + e.getMessage());
			}

			if (connection != null) {
				connection.disconnect();
			}
		}
		return result.toString();
	}


	public String addUser(XyxtXyxxJbxxb xyxtXyxxJbxxb, String token) {
		String httpUrl = addUserUrl;
		StringBuilder result = new StringBuilder();
		HttpURLConnection connection = null;

		try {
			// 创建URL对象
			URL url = new URL(addUserUrl);
			connection = (HttpURLConnection) url.openConnection();

			// 设置连接参数
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(3000);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			connection.setRequestProperty("Authorization", "Bearer " + token);

			// 使用FastJson序列化请求体
			Map<String,Object> map = new HashMap<String,Object>();
			List<Object> list = new ArrayList<>();
			Map permissions = new HashMap<String,Object>();
			permissions.put("hasPermission",true);
			permissions.put("id","");
			permissions.put("permissionCode","Emp_Reserve_Authority");
			permissions.put("permissionValue","Emp_Reserve_Authority_Just");
			permissions.put("ReserveModel","OCCUPANT");
			permissions.put("travelType","COMPANY");
			list.add(permissions);
			map.put("cardId",cardId);
			map.put("cardPassWord",cardPassWord);
			map.put("userNumber", xyxtXyxxJbxxb.getSfzjh()+"001");
			map.put("userName",xyxtXyxxJbxxb.getXm());
			map.put("mobile",xyxtXyxxJbxxb.getPhone());
			map.put("certificateType",certificateType);
			map.put("bookId",cardId);
			map.put("permissions",list);
			String requestBody = JSON.toJSONString(map);
			// 发送请求数据
			try (OutputStream os = connection.getOutputStream();
			     OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
				osw.write(requestBody);
				// os.write(requestBody.getBytes("UTF-8"));
				osw.flush();
			}

			// 获取响应代码
			int responseCode = connection.getResponseCode();

			// 读取响应内容
			if (responseCode == HttpURLConnection.HTTP_OK) {
				try (InputStream is = connection.getInputStream();
				     BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"))) {
					String line;
					while ((line = br.readLine()) != null) {
						result.append(line);
					}
				}
			} else {
				// 错误处理（可选）
				result.append("HTTP Error: ").append(responseCode);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result.toString();
	}


	public String getHxUser(String userNumber, String token) {
		StringBuilder result = new StringBuilder();
		HttpURLConnection connection = null;

		try {
			// 创建URL对象
			URL url = new URL(getHxUserUrl);
			connection = (HttpURLConnection) url.openConnection();

			// 设置连接参数
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(3000);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			connection.setRequestProperty("Authorization", "Bearer " + token);

			// 使用FastJson序列化请求体
			Map<String,Object> map = new HashMap<String,Object>();
			List<Object> list = new ArrayList<>();
			Map permissions = new HashMap<String,Object>();
			permissions.put("hasPermission",true);
			permissions.put("id","");
			permissions.put("permissionCode","Emp_Reserve_Authority");
			permissions.put("permissionValue","Emp_Reserve_Authority_Just");
			permissions.put("ReserveModel","OCCUPANT");
			permissions.put("travelType","COMPANY");
			list.add(permissions);
			map.put("cardId",cardId);
			map.put("cardPassWord",cardPassWord);
			map.put("userNumber", userNumber);
			map.put("permissions",list);
			String requestBody = JSON.toJSONString(map);
			// 发送请求数据
			try (OutputStream os = connection.getOutputStream();
				 OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8")) {
				osw.write(requestBody);
				// os.write(requestBody.getBytes("UTF-8"));
				osw.flush();
			}

			// 获取响应代码
			int responseCode = connection.getResponseCode();

			// 读取响应内容
			if (responseCode == HttpURLConnection.HTTP_OK) {
				try (InputStream is = connection.getInputStream();
					 BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"))) {
					String line;
					while ((line = br.readLine()) != null) {
						result.append(line);
					}
				}
			} else {
				// 错误处理（可选）
				result.append("HTTP Error: ").append(responseCode);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result.toString();
	}


	public static String encrypt(String sSrc, String sKey) {
		if (sKey == null) {
			return null;
		} else if (sKey.length() != 16) {
			return null;
		} else {
			try {
				byte[] raw = sKey.getBytes("utf-8");
				SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
				Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
				cipher.init(1, skeySpec);
				byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
				return Base64.getEncoder().encodeToString(encrypted);
			} catch (Exception var6) {
				// log.error("encrypt get sign error", var6);
				return "";
			}
		}
	}

	public static void main(String[] args) {
		String str = "{'code':400}";

		JSONObject jsonObject1 = JSON.parseObject(str);

		System.out.println(Integer.parseInt(jsonObject1.get("code").toString()));
	}
}
